package com.lagou.filter.component;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.dubbo.common.URL;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;


public class ConsumerMetrics {

    private Map<String, ConcurrentLinkedDeque<Metrics>> metricsMap = new ConcurrentHashMap<>();

    private static final ConsumerMetrics consumerMetrics = new ConsumerMetrics();

    private ConsumerMetrics() {}

    public static ConsumerMetrics getInstance() {
        return consumerMetrics;
    }

    public void putMetrics(String methodName, Metrics metrics) {
        ConcurrentLinkedDeque<Metrics> metricsDeque = metricsMap.computeIfAbsent(methodName, (key) -> new ConcurrentLinkedDeque());
        metricsDeque.add(metrics);
    }

    public Map<String, ConcurrentLinkedDeque<Metrics>> getMetricsMap() {
        return metricsMap;
    }

    @Data
    @AllArgsConstructor
    public static class Metrics implements Comparable<Metrics> {
        private URL url;

        public Long getCostTime() {
            return costTime;
        }

        public void setCostTime(Long costTime) {
            this.costTime = costTime;
        }

        public Long getRequestTime() {
            return requestTime;
        }

        public void setRequestTime(Long requestTime) {
            this.requestTime = requestTime;
        }

        private Long costTime;

        private Long requestTime;

        @Override
        public int compareTo(Metrics o) {
            return this.getCostTime().compareTo(o.getCostTime());
        }
    }

}
